/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: CountServer
 * Author:   zengjian
 * Date:     2018/9/21 16:28
 * Description: CountServer
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package netty.countserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import netty.telnet.TelnetServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 〈CountServer〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/9/21 16:28
 */
public class CountServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(TelnetServer.class);

    private final EventLoopGroup parent = new NioEventLoopGroup();
    private final EventLoopGroup child = new NioEventLoopGroup();
    private volatile AtomicBoolean started = new AtomicBoolean(false);
    private final ServerBootstrap serverBootstrap = new ServerBootstrap();
    private ChannelFuture serverChannelFuture;

    public void start(String host, int port) {
        if (!started.compareAndSet(false, true)) {
            return;
        }
        serverBootstrap.group(parent, child)
                .channel(NioServerSocketChannel.class)
                .childHandler(new CountChildHandler());
        try {
            serverChannelFuture = serverBootstrap.bind(host, port).sync();
            LOGGER.info("listen host:{} port: {}", host, port);
            // closeFuture() no close()
            serverChannelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            Thread.interrupted();
            LOGGER.error("TelnetServer terminate", e);
        }
    }

    public static void main(String[] args) {
        String host = "localhost";
        int port = 8080;
        new CountServer().start(host, port);
    }
}